//
//  TIMAddFriendVC.m
//  Demo_sdk
//
//  Created by Deli Xia on 2018/6/30.
//  Copyright © 2018年 Deli Xia. All rights reserved.
//

#import "TIMAddFriendVC.h"
#import "TIMAddFriendCell.h"
#import "TIMDemoMacro.h"
#import "TIMDemoMacro.h"

#import "TIMApi.h"
#import "TIMStorageModel.h"
#import "TIMStorageManager.h"

@interface TIMAddFriendVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong) NSMutableArray *dataSource;//!<
@property (nonatomic,strong) UITextField *textfiled;//!<
@property (nonatomic,assign) BOOL isNotSearch;//!<

@property (nonatomic, strong) UILabel *searchFriendLabel;
@property (nonatomic, strong) UIButton *addBtn;

@property (nonatomic, strong) TIMUserInfo *searchFriendInfo;

@end

@implementation TIMAddFriendVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isNotSearch = NO;
    self.view.backgroundColor = DefaultBackGroundColor;
    
    [self setUpNav];
}

- (void)setUpNav
{
    [self.navigationController.navigationItem setHidesBackButton:YES];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationController.navigationBar.backItem setHidesBackButton:YES];
    
    UITextField *textfiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, Screen_Width - 45, 30)];
    textfiled.delegate = self;
    textfiled.backgroundColor = RGBColor(240, 240, 240);
    textfiled.layer.cornerRadius = 15;
    textfiled.font = TPSFontSize(13);
    textfiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textfiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.textfiled = textfiled;
    
    UIView *searchBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 35)];
    searchBgView.backgroundColor = [UIColor clearColor];
    
    UIImageView *searchImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Search"]];
    searchImg.frame = CGRectMake(10, 10, 15, 15);
    [searchBgView addSubview:searchImg];
    textfiled.leftView = searchBgView;
    textfiled.leftViewMode = UITextFieldViewModeAlways;
    textfiled.placeholder = @"ID/手机号";
    self.navigationItem.titleView = textfiled;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 33, 33);
    btn.titleLabel.font = TPSFontSize(15);
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, -6);
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(cancelBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)cancelBtnClicked
{
    [self.textfiled resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)getFriInfoWith:(NSString *)userID
{
    NSLog(@"搜索好友：%@", userID);
    [TIMApi queryFriendInfoWithUserId:userID completion:^(NSError *error) {
        if (error) {
            NSLog(@"error %@",error);
            if (error.code == 51007016) {
                 [ProgressHUD showHudTipStr:@"该用户不存在"];
            } else {
                  [ProgressHUD showHudTipStr:@"网络信号差，请检查您的网络设置"];
            }
        } else {
            // 查找成功底层已经存入数据库，从数据库读取
            TIMUserInfo *friend = [[TIMStorageManager sharedStorageManager] getFriendByFriendID:userID];
            self.searchFriendInfo = friend;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.searchFriendLabel.text = [NSString stringWithFormat:@"friend.userid: %@, friend.showname:%@,friend.headurl:%@",friend.userID,friend.showName,friend.avatarURL];
                [self.view addSubview:self.searchFriendLabel];
                [self.view addSubview:self.addBtn];
            });
        }
    }];
    
}


#pragma UITextfiledDelegate
-(void)textFieldDidChange :(UITextField *)textField
{
    [self.dataSource removeAllObjects];
    
    if (textField.markedTextRange == nil) {
        NSLog(@"text:%@", textField.text);
        if (textField.text.length > 0) {
            if (!self.isNotSearch) {
                [self.dataSource addObject:@""];
            } else {
                self.isNotSearch = NO;
                [self.dataSource addObject:@""];
            }
        } else {
            self.isNotSearch = NO;
        }
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length > 0) {
        
        [self.textfiled resignFirstResponder];
        
        [self getFriInfoWith:self.textfiled.text];
        
        return YES;
    }
    return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //如果是限制只能输入数字的文本框
    if (self.textfiled == textField) {
        
        return [self validateNumber:string];
        
    }
    //否则返回yes,不限制其他textfield
    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res =YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i =0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i,1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length ==0) {
            res =NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)addFriend {
    TIMUserInfo *user = [[TIMStorageManager sharedStorageManager] getCurrentUserInfo];
    [TIMApi addFriendWithSenderId:user.userID ReceiverId:self.searchFriendInfo.userID MsgMemo:self.searchFriendInfo.remarkName MsgGroup:[@"fenzu" dataUsingEncoding:NSUTF8StringEncoding] MsgTip:[@"我好帅" dataUsingEncoding:NSUTF8StringEncoding]MsgOperation:TIMMsgOperation_OperationFriAdd completion:^(NSError *error) {
        if (!error) {
            NSLog(@"发送添加好友请求成功");
            dispatch_async(dispatch_get_main_queue(), ^{
                 [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            [ProgressHUD showHudTipStr:@"添加失败"];
        }
    }];
}

#pragma mark - Get

- (UILabel *)searchFriendLabel {
    if (!_searchFriendLabel) {
        _searchFriendLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, Screen_Width, 100)];
        _searchFriendLabel.numberOfLines = 0;
        _searchFriendLabel.backgroundColor = UIColor.whiteColor;
        _searchFriendLabel.textColor = UIColor.blackColor;
    }
    return _searchFriendLabel;
}

- (UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        _addBtn.frame = CGRectMake(100, 300, 100, 40);
        [_addBtn setTitle:@"添加好友" forState:UIControlStateNormal];
        [_addBtn setTitleColor:UIColor.redColor forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(addFriend) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}
@end
